<template>
  <div>
    <ul>
      <li v-for="event in events" :key="event.id">{{ event.data }}</li>
    </ul>
  </div>
</template>

<script>
import { ref, onUnmounted } from "vue";
import { EventSourcePolyfill } from "event-source-polyfill";
export default {
  setup() {
    const events = ref([
      {
        id: 1,
        data: "123",
      },
      {
        id: 2,
        data: "456",
      },
    ]);

    const eventSource = new EventSourcePolyfill(
      "http://127.0.0.1:8081/events",
      {
        headers: {
          "X-Custom-Header": "value",
        },
      }
    );

    eventSource.addEventListener("open", function (e) {
      console.log("open successfully", e);
    });

    eventSource.addEventListener("message", function (e) {
      console.log(111, events.value, e.data);
      events.value.push({
        id: events.value.length + 1,
        data: e.data,
      });
    });

    eventSource.addEventListener("error", function (err) {
      console.log(err);
      err && err.status === 401 && console.log("not authorized");
    });
    const closeEventSource = () => {
      console.log(222222222222222222);
      eventSource.close();
    };
    onUnmounted(closeEventSource);
    return {
      events,
    };
  },
  onUnmounted() {},
};
</script>
